package com.tramp.frame.server.exception;

import com.tramp.frame.server.base.CodeEnum;
import com.tramp.frame.server.base.ResultData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理
 * Created by chen on 2017/10/21.
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 业务异常处理
     * @param request
     * @param response
     * @param e
     * @return
     */
    @ExceptionHandler(value = GenericException.class)
    @ResponseBody
    public ResultData defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        logger.error("GenericException:", e);
        return ResultData.error(CodeEnum.GENERICEXCEPTION_CODE.getValue(),e.getMessage());
    }

    /**
     * 未知的运行时异常
     * @author fengshuonan
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResultData notFount(RuntimeException e) {
        logger.error("500,Internal Server Error:", e);
        return ResultData.error(CodeEnum.SERVER_ERROE.getValue(),e.getMessage());
    }
}
